const labelService = require("../service/label.service")

/**
 * 传入的labels 判断是否有 有的话就跳过 没有就添加入数据库
 * @param {*} ctx 
 * @param {*} next 
 */
const verifyLabelExist = async (ctx, next) => {
  // 1.先获取客户端传递过来的labels
  const { labels } = ctx.request.body
  // 2.判断所有labels中name是否已经存在
  const newLabels = []
  for (const name of labels) {
    const result = await labelService.queryLabelByName(name)
    const labelObj = { name }
    if(result) {
      // 拿一下id
      labelObj.id = result.id
      console.log(result.id)
    }else {
      // 插入name 并且获取插入之后的id
      const insertResult = await labelService.create(name) 
      labelObj.id = insertResult.insertId
    }
    newLabels.push(labelObj)
  }

  // 3.所以的labels都变成了 [{name: '', id: }]
  ctx.labels = newLabels
  await next()
}

module.exports = {
  verifyLabelExist
}
